package cn.it.xiaohan.note.web;

import cn.it.xiaohan.note.po.User;
import cn.it.xiaohan.note.service.UserService;
import cn.it.xiaohan.note.vo.ResultInfo;
import org.apache.commons.io.FileUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/user")
@MultipartConfig
public class UserServlet extends HttpServlet {
    private UserService userService = new UserService();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 设置个人中心高亮
        request.setAttribute("menu_page","user");

        String actionName = request.getParameter("actionName");

        if ("login".equals(actionName)){

            // 用户登录
            userLogin(request,response);
        } else if ("logout".equals(actionName)){

            // 用户退出操作
            userLogout(request,response);
        } else if ("userCenter".equals(actionName)){

            // 进入个人中心
            userCenter(request,response);
        } else if ("userHead".equals(actionName)){

            // 加载头像
            userHead(request,response);
        } else if ("checkNick".equals(actionName)){

            // 验证昵称唯一性
            checkNick(request,response);
        } else if ("updateUser".equals(actionName)){

            // 修改用户信息
            updateUser(request,response);
        }
    }

    private void updateUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 调用Service方法，将request作为参数传过去
        ResultInfo<User> resultInfo = userService.updateUser(request);
        // 将返回的对象存入到request域中
        request.setAttribute("resultInfo",resultInfo);
        request.getRequestDispatcher("user?actionName=userCenter").forward(request,response);
    }

    private void checkNick(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String nickName = request.getParameter("nick");
        User user = (User) request.getSession().getAttribute("user");
        Integer code = userService.checkNick(nickName,user.getUserId());
        PrintWriter out = response.getWriter();
        out.write(code + "");
        out.close();
    }

    private void userHead(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取参数
        String head = request.getParameter("imageName");
        // 获取图片的存放路径
        String realPath = request.getServletContext().getRealPath("/statics/images/");

        // 通过图片的完整路径得到file对象
        File file = new File(realPath+head);
        // 得到图片后缀
        String pic = head.substring(head.lastIndexOf(".") + 1);
        // 通过不同的后缀相应不同的类型
        if ("PNG".equalsIgnoreCase(pic)){
            response.setContentType("image/png");
        } else if ("JPG".equalsIgnoreCase(pic) || "JPEG".equalsIgnoreCase(pic)){
            response.setContentType("image/jpeg");
        } else if ("GIF".equalsIgnoreCase(pic)){
            response.setContentType("image/gif");
        }
        // 利用FileUtils的copy方法将图片拷贝给浏览器
        FileUtils.copyFile(file,response.getOutputStream());
    }

    /**
     * 进入个人中心
     * 1.设置首页动态包含的页面值
     * 2.请求转发跳转到index.jsp
     * @param request
     * @param response
     */
    private void userCenter(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置首页动态包含的页面值
        request.setAttribute("changePage","user/info.jsp");
        // 请求转发跳转到index.jsp
        request.getRequestDispatcher("index.jsp").forward(request,response);
    }

    private void userLogout(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // 1.清空Session对象
        request.getSession().invalidate();
        // 2、清空cookie对象
        Cookie cookie = new Cookie("user",null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        // 3、从定向到登录页面
        response.sendRedirect("login.jsp");
    }


    private void userLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String userName = request.getParameter("userName");
        String userPwd = request.getParameter("userPwd");

        ResultInfo<User> resultInfo = userService.userLogin(userName,userPwd);

        if (resultInfo.getCode() == 1){
            request.getSession().setAttribute("user",resultInfo.getResult());
            String rem = request.getParameter("rem");
            if ("1".equals(rem)){
                Cookie cookie = new Cookie("user",userName +"-"+ userPwd);
                cookie.setMaxAge(7 * 24 * 60 * 60);
                response.addCookie(cookie);
            }else{
                Cookie cookie = new Cookie("user",null);
                cookie.setMaxAge(0);
                response.addCookie(cookie);
            }
            response.sendRedirect("index");

        } else {
            request.setAttribute("resultInfo",resultInfo);
            request.getRequestDispatcher("login.jsp").forward(request,response);
        }
    }
}
